package com.potenza.training.reply.controller;

import com.potenza.training.reply.dao.AopDao;
import com.potenza.training.reply.entity.AopEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Aspect
@Component
public class TestAop {

    @Autowired
    AopDao aopDao;
    private static final Logger Logger = LogManager.getLogger(TestAop.class);

    @Pointcut("execution(* com.potenza.training.reply.service.impl.*.*(..))")
    public void logPointCutOne() {

    }
    @Pointcut("@annotation(org.springframework.transaction.annotation.Transactional)")
    public void logPointCutTwo() {

    }

    @Around("logPointCutOne()||logPointCutTwo()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        AopEntity aopEntity = new AopEntity();
        //获取有注解的方法
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取方法类型及名称
        String className = methodSignature.getDeclaringType().getSimpleName();
        String methodName = methodSignature.getName();

        //设置秒数
        final StopWatch stopWatch = new StopWatch();
        //开始时间
        long beginTime = System.currentTimeMillis();
        System.out.print("开始时间"+beginTime);
        //Measure method execution time
        stopWatch.start();
        Object result = proceedingJoinPoint.proceed();
        //结束时间
        stopWatch.stop();
        long endTime = System.currentTimeMillis();
        System.out.print("结束时间"+endTime);


        //Log method execution time
        Logger.info("Execution time of " + className + "." + methodName + " "+ ":: "+stopWatch.getTotalTimeMillis()+ " ms");
        aopEntity.setBeginTime(beginTime);
        aopEntity.setEndTime(endTime);
        aopEntity.setClassName(className);
        aopEntity.setMethodName(methodName);
        aopDao.insert(aopEntity);
        return result;
    }


}
